﻿using System;
using System.Web.UI.WebControls;
using Cms.Data;
using Cms.Domain;
using Cms.Domain.RepositoryInterfaces;
using Cms.Utilities;
using Content = Cms.Domain.Content;

namespace Cms.Web.Framework.Plugins
{
    public class ListComments : BaseTemplatedPlugin
    {
        // Property fields
        private int _contentID;

        // Template controls
        private Repeater rpComments;

        public int ContentID
        {
            get { return _contentID; }
            set { _contentID = value; }
        }
        
        protected override void CreateChildControls()
        {
            try
            {
                base.CreateChildControls();
                rpComments = (Repeater)FindControl("rpComments");
                rpComments.ItemDataBound += rpComments_ItemDataBound;
            }
            catch (Exception ex)
            {
                Logging.LogError("ListComments", ex);
                Controls.Clear();
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            if (_contentID > 0)
            {
                IContentRepository contentRepository = new ContentRepository();
                Content content = contentRepository.GetContent(_contentID);
                rpComments.DataSource = content.Comments;
            }
            else if (RequestDetails.Page != null)
                rpComments.DataSource = RequestDetails.Page.Comments;
            rpComments.DataBind();
        }

        private void rpComments_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem)
                return;
            var comment = (Comment)e.Item.DataItem;
            var litTimestamp = (Literal)e.Item.FindControl("litTimestamp");
            var litName = (Literal)e.Item.FindControl("litName");
            var litComment = (Literal)e.Item.FindControl("litComment");
            litTimestamp.Text = comment.Created.ToString();
            litName.Text = comment.Name;
            litComment.Text = comment.Text;
        }
    }
}